<template>
	<view class="row flex-center">
		<view class="q-pr-sm text-primary">
			{{标题}}{{加冒号否?':':'' }}
		</view>
		<template v-if="编辑">
			<uni-easyinput v-model="modelValue" :placeholder="placeholder" v-bind="$attrs" :style="style" ref="inputRef"
				@focus="onFocus" @blur="onBlur" :clearable="showClearIcon" @clear="handleClear" />
		</template>

		<template v-else>
			{{modelValue}}
		</template>
	</view>
</template>

<script setup>
	import { computed, ref, watch } from 'vue';

	const props = defineProps({
		标题: {
			type: String,
			default: ""
		},
		加冒号否: {
			type: Boolean,
			default: true
		},
		编辑: {
			type: Boolean,
			default: false
		},
		placeholder: {
			type: String,
			default: "请输入……"
		},
		width: {
			type: [String, Number],
			default: 200
		},

	});

	const modelValue = defineModel();
	const inputRef = ref(null);
	const isFocused = ref(false); // 记录输入框是否聚焦
	const showClearIcon = ref(false); // 控制清除图标的显示

	const style = computed(() => {
		const res = {}
		if (props.width !== 0) {
			res.width = props.width + 'rpx'
		}
		return res
	});

	// 计算属性：统一转为字符串，避免类型问题
	const stringValue = computed(() => {
		const value = modelValue.value;
		return typeof value === 'number' ? value.toString() : String(value);
	});
	// 监听输入框内容变化，当聚焦且有内容时显示清除图标
	watch(stringValue, (value) => {
		if (isFocused.value && value.trim() !== '') {
			showClearIcon.value = true;
		} else if (!isFocused.value) {
			showClearIcon.value = false;
		}
	});

	const onFocus = () => {
		isFocused.value = true;
		const value = stringValue.value;
		if (value.trim() !== '') { // 此时 value 一定是字符串，可安全调用 trim()
			showClearIcon.value = true;
		}
	};

	const onBlur = () => {
		isFocused.value = false;
		const value = stringValue.value;
	};

	const handleClear = () => {
		modelValue.value = ''; 
		showClearIcon.value = false; 
	};

	defineExpose({
		focusInput: () => {
			const el = inputRef.value.$el;
			const inputel = el.querySelectorAll("input")[0];
			if (inputel) {
				inputel.focus();
				// // 聚焦后立即检查内容并更新清除图标的显示状态
				// if (modelValue.value && modelValue.value.trim() !== '') {
				// 	showClearIcon.value = true;
				// }
			}
		}
	});
</script>